//
//  FPAddressPopupView.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/24.
//

#import "FPAddressPopupView.h"
#import "FPCitiesModel.h"

#define PickerHeight 520.f

@interface FPAddressPopupView () <UITableViewDelegate, UITableViewDataSource , UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITableView *provinceTableView;
@property (nonatomic, strong) UITableView *cityTableView;
//@property (nonatomic, strong) UITableView *districtTableView;

@property (nonatomic, strong) NSMutableArray *provinces;  // 所有省份
@property (nonatomic, strong) NSMutableArray *cities;     // 当前选择省份的城市
//@property (nonatomic, strong) NSArray *districts;  // 当前选择城市的区

@property (nonatomic, strong) NSString *selectedProvince;  // 当前选中的省
@property (nonatomic, strong) NSString *selectedCity;     // 当前选中的市
//@property (nonatomic, strong) NSString *selectedDistrict; // 当前选中的区

@property (nonatomic, strong) UIView *backgroundView;  // 半透明背景视图
@property (nonatomic , strong) UIView *pickerContainer;

@property (nonatomic , assign) NSInteger provinceIndex;
@property (nonatomic , assign) NSInteger cityIndex;

@end

@implementation FPAddressPopupView

LazyLoadDataSource(provinces)
LazyLoadDataSource(cities)

- (instancetype)initWithAddressData:(NSDictionary *)data {
    self = [super init];
    if (self) {
        
        [FPCitiesModel getCitiesSuccess:^(NSArray * _Nonnull list) {
            
            for (FPCitiesModel *model in list) {
                
                [self.provinces addObject:model];
            }
            
            [self setupUI];
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
                    
            
            
        
//        self.addressData = data;
//        self.provinces = [data allKeys];  // 获取所有省份
//        
//        for (NSDictionary *province in provinceArray) {
//            NSString *provinceName = province[@"province"];
//            NSArray *cities = province[@"cities"];
//            NSLog(@"省：%@", provinceName);
//
//            for (NSDictionary *city in cities) {
//                NSString *cityName = city[@"city"];
//                NSArray *areas = city[@"areas"];
//                NSLog(@"\t市：%@", cityName);
//                
//                for (NSString *area in areas) {
//                    NSLog(@"\t\t区：%@", area);
//                }
//            }
//        }
        
       
    }
    return self;
}

- (void)setupUI {
    // 设置背景视图
    self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
    [self addSubview:self.backgroundView];
    
    // 创建选择器的容器视图
    self.pickerContainer = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - PickerHeight, SCREEN_WIDTH, PickerHeight)];
    self.pickerContainer.backgroundColor = [UIColor whiteColor];
    
    [self.backgroundView addSubview:self.pickerContainer];
    
    // 创建省、市、区的 UITableView
    self.provinceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, PickerHeight) style:UITableViewStylePlain];
    self.cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 3, PickerHeight) style:UITableViewStylePlain];
//    self.districtTableView = [[UITableView alloc] initWithFrame:CGRectMake(2 * SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 3, PickerHeight) style:UITableViewStylePlain];
    
    self.provinceTableView.delegate = self;
    self.provinceTableView.dataSource = self;
    self.cityTableView.delegate = self;
    self.cityTableView.dataSource = self;
//    self.districtTableView.delegate = self;
//    self.districtTableView.dataSource = self;
    
    self.provinceTableView.showsVerticalScrollIndicator = NO;
    self.cityTableView.showsVerticalScrollIndicator = NO;
//    self.districtTableView.showsVerticalScrollIndicator = NO;
    self.provinceTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.cityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    self.districtTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.pickerContainer addSubview:self.provinceTableView];
    [self.pickerContainer addSubview:self.cityTableView];
//    [self.pickerContainer addSubview:self.districtTableView];
    
    // 添加点击背景关闭手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [self.backgroundView addGestureRecognizer:tapGesture];
    tapGesture.delegate = self;
}

- (void)show {
    // 弹出动画：背景变为半透明，并将选择器从下往上滑动
//    [UIView animateWithDuration:0.3 animations:^{
//        self.backgroundView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.5f];
//        self.pickerContainer.frame = CGRectMake(0, SCREEN_HEIGHT - PickerHeight, SCREEN_WIDTH, PickerHeight);
//    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:.25f animations:^{
            
            self.backgroundView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.5f];
        }];
    }];
}

- (void)dismiss {
    // 关闭动画：选择器滑出并隐藏背景
//    [UIView animateWithDuration:0.3 animations:^{
//        self.backgroundView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.f];
//        self.pickerContainer.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
//    }];
    
    self.backgroundView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.f];
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

// 获取每列的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.provinceTableView) {
        return self.provinces.count;
    } else {
        
        FPCitiesModel *model = self.provinces[self.provinceIndex];
        return model.cityChild.count;
    }
}

// 配置每行的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    cell.selectionStyle = 0;
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    if (tableView == self.provinceTableView) {
     
        FPCitiesModel *model = self.provinces[indexPath.row];
        cell.textLabel.text = model.extName;
    } else {
        
        FPCitiesModel *model = self.provinces[self.provinceIndex];
        FPCitiesChild *m = model.cityChild[indexPath.row];
        cell.textLabel.text = m.extName;
    }
    
    return cell;
}

// 处理用户选择的省份
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.provinceTableView) {
        
        self.provinceIndex = indexPath.row;
        
        FPCitiesModel *model = self.provinces[indexPath.row];
//        self.cities = [[self.addressData[self.selectedProvince] firstObject] allKeys]; // 更新市数据
        
        self.selectedProvince = model.ID;
        
        if ([model.provinceName containsString:@"北京"] || [model.provinceName containsString:@"重庆"] || [model.provinceName containsString:@"上海"] || [model.provinceName containsString:@"天津"] ||
            [model.provinceName containsString:@"香港"] || [model.provinceName containsString:@"澳门"] || [model.provinceName containsString:@"台湾"]) {
            
            self.selectionBlock(model.extName , model.provinceName , self.selectedProvince);
            [self.cityTableView reloadData];
            [self dismiss];  // 选择完毕，关闭选择器
            return;
        }
        
        for (FPCitiesChild *child in model.cityChild) {
            
            [self.cities addObject:child];
        }
        
        [self.cityTableView reloadData];
        
//        self.districts = @[];
//        [self.districtTableView reloadData];
    }
    else {
        
        self.cityIndex = indexPath.row;
        
        FPCitiesModel *model = self.provinces[self.provinceIndex];
        FPCitiesChild *child = model.cityChild[indexPath.row];
//        self.districts = [self.addressData[self.selectedProvince] firstObject][self.selectedCity];
//        [self.districtTableView reloadData];
        
        self.selectedProvince = child.ID;
        self.selectionBlock(child.provinceName , child.extName , self.selectedProvince);
        [self dismiss];  // 选择完毕，关闭选择器
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    if ([touch.view isEqual:self.backgroundView]) {

//        self.showTabBarBlock();
        return YES;
    }

    return NO;
}

@end
